package com.mastercard.labs

import org.springframework.dao.DataIntegrityViolationException

class MerchantController {
	
	def merchantService
	def categoryService
	def countryService

    static allowedMethods = [save: "POST", delete: "POST"]

    def index() {
        redirect(action: "search", params: params)
    }

	def search(){
		if(params.prevAction == "dashboard"){
			redirect(controller: "dashboard")
		}else if(params.search == "Search"){
			perform()
		}else{
			if(null != params.searchCondition && !"".equals(params.searchCondition)){
				String[] str = params.searchCondition.split("#")
				params.searchName = str[0]
				params.searchCountry = str[1]
				params.searchCategory = str[2]
				params.searchStatus = str[3]
				
				perform()
			}else{
				def catList = categoryService.getAll()
				def countryList = countryService.getAll()
				[catList: catList, countryList: countryList]
			}
		}
	}

	private def perform(){
		if(!params.searchName){
			params.searchName = ""
		}
		if(!params.searchCountry){
			params.searchCountry = ""
		}
		if(!params.searchCategory){
			params.searchCategory = ""
		}
		if(!params.searchStatus){
			params.searchStatus = ""
		}
		println(params.searchCountry)
		def merchantInstanceList = merchantService.searchMerchantByCondition(params.searchName, params.searchCountry, params.searchCategory, params.searchStatus)
		def searchCondition = params.searchName + "#" + params.searchCountry + "#" + params.searchCategory + "#" + params.searchStatus + "#NA#"
		println("Search Condition = " + searchCondition)
		
		def catList = categoryService.getAll()
		def countryList = countryService.getAll()
		
		[merchantInstanceList: merchantInstanceList,
		 searchCondition: searchCondition,
		 searchName: params.searchName,
		 searchCountry: params.searchCountry,
		 searchCategory: params.searchCategory,
		 searchStatus: params.searchStatus,
		 catList: catList,
		 countryList: countryList
		]
	}
	
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [merchantInstanceList: Merchant.list(params), merchantInstanceTotal: Merchant.count()]
    }

    def create() {
        [merchantInstance: new Merchant(params)]
    }
	
	def save() {
		def merchantInstance, catList, countryList
		
		if(params.id){
			merchantInstance = merchantService.getMerchantById(params.id)
			if (!merchantInstance) {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.name])
				redirect(action: "search", model: [searchCondition: params.searchCondition])
				return
			}
	
			if (params.version) {
				def version = params.version.toLong()
				if (merchantInstance.version > version) {
					catList = categoryService.getAll()
					countryList = countryService.getAll()
					
					merchantInstance.errors.rejectValue("version", "default.optimistic.locking.failure", 
							  [message(code: 'merchant.label', default: 'Merchant')] as Object[],
							  "Another user has updated this Merchant while you were editing")
					render(view: "update", model: [merchantInstance: merchantInstance, searchCondition: params.searchCondition, catList: catList, countryList: countryList])
					return
				}
			}
		}else{
			merchantInstance = new Merchant()
		}
		
		merchantInstance.name = params.name
		merchantInstance.country = countryService.getCountryById(params.country)
		merchantInstance.description = params.description
		merchantInstance.contact = params.contact
		merchantInstance.logo = params.logo
		merchantInstance.address = params.address
		merchantInstance.status = Merchant.Status.valueOf(params.status)
		
		def index = 0, arrSize = 0
		if(params.categories){
			arrSize = params.categories.size()
		}
		def tmpArr = new Long[arrSize]
		for(String ids: params.categories){
			tmpArr[index++] = Long.valueOf(ids)
		}
		if(0 < tmpArr.length){
			catList = categoryService.getCategoryListByIds(tmpArr)
			merchantInstance.categories = catList
		}
						
		if(merchantInstance.validate()){
			merchantService.saveMerchant(merchantInstance)
			
			if(params.id){
				flash.message = message(code: 'default.updated.message', args: [message(code: 'merchant.label', default: 'Merchant'), merchantInstance.name])
			}else{
				flash.message = message(code: 'default.created.message', args: [message(code: 'merchant.label', default: 'Merchant'), merchantInstance.name])
			}
			redirect(action: "search",  params: [searchCondition: params.searchCondition])
		}else{
			catList = categoryService.getAll()
			countryList = countryService.getAll()
			render(view: "update", model: [merchantInstance: merchantInstance, searchCondition: params.searchCondition, catList: catList, countryList: countryList])
		}
	}
/*
    def save() {
        def merchantInstance = new Merchant(params)
        if (!merchantInstance.save(flush: true)) {
            render(view: "create", model: [merchantInstance: merchantInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'merchant.label', default: 'Merchant'), merchantInstance.id])
        redirect(action: "show", id: merchantInstance.id)
    }
*/
    def show() {
        def merchantInstance = Merchant.get(params.id)
        if (!merchantInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.id])
            redirect(action: "list")
            return
        }

        [merchantInstance: merchantInstance]
    }

    def edit() {
        def merchantInstance = Merchant.get(params.id)
        if (!merchantInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.id])
            redirect(action: "list")
            return
        }

        [merchantInstance: merchantInstance]
    }

	def update() {
		def merchantInstance = new Merchant()
		
		if(params.id){
			merchantInstance = merchantService.getMerchantById(params.id)
			
			if (!merchantInstance) {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.id])
				redirect(action: "search", params: [searchCondition: params.searchCondition])
				return
			}
		}
		
		def catList = categoryService.getAll()
		def countryList = countryService.getAll()
		
		[merchantInstance: merchantInstance, searchCondition: params.searchCondition, catList: catList, countryList: countryList, prevAction: params.prevAction]
	}
/*	
    def update() {
        def merchantInstance = Merchant.get(params.id)
        if (!merchantInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (merchantInstance.version > version) {
                merchantInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'merchant.label', default: 'Merchant')] as Object[],
                          "Another user has updated this Merchant while you were editing")
                render(view: "edit", model: [merchantInstance: merchantInstance])
                return
            }
        }

        merchantInstance.properties = params

        if (!merchantInstance.save(flush: true)) {
            render(view: "edit", model: [merchantInstance: merchantInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'merchant.label', default: 'Merchant'), merchantInstance.id])
        redirect(action: "show", id: merchantInstance.id)
    }
*/
    def delete() {
        def merchantInstance = Merchant.get(params.id)
        if (!merchantInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.name])
            redirect(action: "update", params: [searchCondition: params.searchCondition, id: params.id])
			return
        }

		merchantInstance.deleled = Boolean.valueOf(true)
        merchantService.saveMerchant(merchantInstance)
		
		flash.message = message(code: 'default.deleted.message', args: [message(code: 'merchant.label', default: 'Merchant'), params.name])
        redirect(action: "search",  params: [searchCondition: params.searchCondition])
    }
	
//	private validateForm(err){
//		if(){
//			err.rejectValue("name", "errors.required", ["Name"] as Object[], "Name is required.")
//		}
//	}
}
